import React, { Component } from 'react';
import FontIcon from 'material-ui/FontIcon';
import Snackbar from 'material-ui/Snackbar';
import RaisedButton from 'material-ui/RaisedButton';
import CircularProgress from 'material-ui/CircularProgress';

import { push } from 'react-router-redux';

import Corp from '../Utils/Corp';
import CONFIG from '../../config';
import EditUserImg from './EditUserImg';
import EditBasicInfo from './EditBasicInfo';
import EditOtherInfo from './EditOtherInfo';
import { dateFormat } from '../Utils/Helper';
import EditSchoolInfo from './EditSchoolInfo';
import { tokenExpired } from '../../redux/actions/LayoutsAc';
import { checkHttpStatus, parseJSON, getMethod, postJsonMethod } from '../../redux/Helper';

export default class Profile extends Component {
  constructor(props) {
    super(props);
    this.state = {
      token: localStorage.getItem('IMLOOKE_COM_USER_TOKEN'),
      userId: localStorage.getItem('IMLOOKE_COM_USER_USERID'),
      userName: null,
      userImg: CONFIG.devHost + '/images/male.png',
      wrap: CONFIG.devHost + '/images/b03.png',
      sex: null,
      state: null,
      birth: null,
      college: null,
      professional: null,
      studentId: null,
      collegeEntry: null,
      notes: null,
      wrapUploadCanvas: null,
      userImgUploadCanvas: null,
      error: null,
      open: false,
      method: 'wrap',
      isPosting: false,
      isSmallViewport: false,
      // Snackbar
      openSnackbar: false,
      message: ''
    };
  }
  
  componentWillMount() {
    if (window.innerWidth <= 768) {
      this.setState({isSmallViewport: true});
    }

    let url = CONFIG.apiHost + '/api/user/' + this.state.userId + '?token=' + this.state.token;
    fetch(url, getMethod)
    .then(parseJSON)
    .then(res => {
      if (!res.msg.is_new_user) {
        this.props.dispatch(push('/i'));
      }

      if (res.error) {
        this.props.dispatch(tokenExpired());
      }
    });
  }

  componentDidMount() {
    window.addEventListener('resize', this.onWindowResive);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.onWindowResive);
  }

  /**
   * 窗口变化事件
   */
  onWindowResive = () => {
    if (window.innerWidth <= 768) {
      this.setState({isSmallViewport: true});
    } else {
      this.setState({isSmallViewport: false});
    }
  };

  /**
   * 修改画布值
   */
  handleChange =(event, name, value, canvas) => {
    this.setState({[name]: value, [name + 'UploadCanvas']: canvas});
  };

  /**
   * 修改普通文本框值
   */
  handleChangeText = (name, event, value) => {
    this.setState({[name]: value});
  };

  /**
   * 修改日期值
   */
  handleChangeDate = (name, event, value) => {
    this.setState({[name]: dateFormat(value)});
  };
  
  /**
   * 修改选择框值
   */
  handleChangeSelect = (name, event, index, value) => {
    this.setState({[name]: value});
  };

  /**
   * 修改选择框值2
   */
  handleChangeSelectValue = (name, value) => {
    this.setState({[name]: value});
  };

  /**
   * 开启会话框
   */
  handleOpen = (method) => {
    this.setState({method: method, open: true});
  };

  /**
   * 关闭会话框
   */
  handleClose = () => {
    this.setState({open: false});
  };

  /**
   * 开启Snackbar
   */
  handleOpenSnackbar = (message) => {
    this.setState({
      openSnackbar: true,
      message,
    });
  };

  /**
   * 关闭Snackbar
   */
  handleCloseSnackbar = () => {
    this.setState({
      openSnackbar: false,
      message: '',
    });
  };

  /**
   * 初始化表单值
   */
  handleCreate = () => {
    let data = {
      user_id: this.state.userId,
      user_name: this.state.userName,
      user_img: this.state.userImg,
      wrap: this.state.wrap,
      sex: this.state.sex,
      state: this.state.state,
      birth: this.state.birth,
      college: this.state.college,
      professional: this.state.professional,
      student_id: this.state.studentId,
      college_entry: this.state.collegeEntry,
      notes: this.state.notes
    }

    if (this.state.userImgUploadCanvas) {
      var dataURL = this.state.userImgUploadCanvas.toDataURL('image/jpeg', 0.6);
      data.user_img = dataURL;
    }

    if (this.state.wrapUploadCanvas) {
      var dataURL = this.state.wrapUploadCanvas.toDataURL('image/jpeg', 0.6);
      data.wrap = dataURL;
    }

    this.post(data);
  };

  /**
   * 提交
   */
  post = (data) => {
    this.setState({isPosting: true});
    fetch(CONFIG.apiHost + '/api/user?token=' + this.state.token, postJsonMethod(data))
    .then(checkHttpStatus)
    .then(parseJSON)
    .then(res => {
      if (res.status) {
        this.setState({isPosting: false});
        this.props.dispatch(push('/i'));
      }
    })
    .catch(e => {
      Promise.resolve(e.res.json()).then(v => {
        this.setState({isPosting: false, error: v.msg});
        if (v.error) {
          this.props.dispatch(tokenExpired());
        }
      })
    })
  };

  render() {
  	return (
      <div style={styles.wrap}>
        <div style={styles.head}>
          <p style={styles.h1}>你已成功注册，现在，请完善个人信息</p>
          <p style={styles.p}>请填写你真实的个人信息，其他用户将会由此发现你</p>
        </div>
        <div style={styles.body}>
          <EditUserImg
            error={this.state.error}
            wrap={this.state.wrap}
            userImg={this.state.userImg}
            userName={this.state.userName}
            handleOpen={this.handleOpen}
            handleChangeText={this.handleChangeText}
          />

          <div style={styles.step}>1. 学生认证</div>

          <EditSchoolInfo 
            error={this.state.error}
            college={this.state.college}
            professional={this.state.professional}
            studentId={this.state.studentId}
            collegeEntry={this.state.collegeEntry}
            handleChangeText={this.handleChangeText}
            handleChangeSelect={this.handleChangeSelect}
            handleChangeSelectValue={this.handleChangeSelectValue}
          />

          <div style={styles.step}>2. 基本信息（可选）</div>

          <EditBasicInfo 
            sex={this.state.sex}
            state={this.state.state}
            birth={new Date()}
            handleChangeText={this.handleChangeText}
            handleChangeDate={this.handleChangeDate}
            handleChangeSelect={this.handleChangeSelect}
          />

          <div style={styles.step}>3. 其他信息（可选）</div>

          <EditOtherInfo 
            error={this.state.error}
            handleChangeText={this.handleChangeText}
          />
          
          <div style={styles.step}>
            <RaisedButton
              labelPosition="before"
              primary={true}
              icon={this.state.isPosting ? '' : <FontIcon className="icon-check" />}
              onClick={this.handleCreate.bind(this)}
              label={this.state.isPosting ? '' : '确认无误，提交'}
              children={this.state.isPosting 
                ? <CircularProgress 
                  style={styles.circularProgress} 
                  size={24} 
                  color="#fff"/> 
                : ''
              }
            />
          </div>

          <div style={styles.foot}></div>
        </div>

        <Corp 
          open={this.state.open}
          method={this.state.method}
          handleClose={this.handleClose}
          handleChange={this.handleChange}
          isSmallViewport={this.state.isSmallViewport}
          handleOpenSnackbar={this.handleOpenSnackbar}
        />
        <Snackbar
          open={this.state.openSnackbar}
          message={this.state.message}
          autoHideDuration={4000}
          onRequestClose={this.handleCloseSnackbar}
        />
      </div>
  	);
  }
};

const styles = {
  wrap: {
    display: 'flex',
    minHeight: '100vh',
    flexDirection: 'column',
  },
  head: {
    paddingTop: 64,
    paddingLeft: 16,
    paddingRight: 24,
    paddingBottom: 128,
    height: 124,
    backgroundColor: '#2196F3',
    textAlign: 'center'
  },
  h1: {
    color: '#fff',
    marginTop: 30,
    fontSize: 34
  },
  p: {
    color: '#fff',
    marginTop: 20,
    fontSize: 20
  },
  body: {
    marginTop: -108,
    padding: 8
  },
  step: {
    textAlign: 'center', 
    padding: 16, 
    fontSize: 16, 
    color: 'rgb(117,117,117)'
  },
  foot: {
    height: 56
  },
  circularProgress: {
    margin: 6
  }
};